package com.lujieni.dbsharding.simple.sharding;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collection;

/**
 * 分库策略类,分库键只支持 == 和 in查询
 */
public class DatabaseShardingAlgorithm implements PreciseShardingAlgorithm<Long> {

    Logger logger = LoggerFactory.getLogger(DatabaseShardingAlgorithm.class);

    /**
     *
     * @param collection m1,m2
     * @param preciseShardingValue 当前分片字段的值
     * @return
     */
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Long> preciseShardingValue) {
        for (String each : collection) {
            // .hashCode()方法返回的值有可能为负数所以要取绝对值
            if (each.equals("m" + (Math.abs(preciseShardingValue.getValue().hashCode()) % 2 + 1))) {
                logger.info("sharding key {}, sharding result {}", preciseShardingValue.getValue(), each);
                return each;
            }
        }
        throw new IllegalArgumentException();
    }

}
